package megrez.mail.sender.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import megrez.mail.sender.common.MailMessage;
import megrez.mail.sender.component.MailSenderComponent;
import megrez.mail.sender.component.template.TemplateProcessFactory;
import megrez.mail.sender.domain.QueryService;
import megrez.mail.sender.domain.TemplateConfig;
import megrez.mail.sender.domain.TemplateContent;

/**
 * 邮件接口
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@RestController
@RequestMapping("/v1/mails")
public class MailResource {
    @Autowired
    private QueryService querySrc;
    @Autowired
    private TemplateProcessFactory templateProcessFactory;
    @Autowired
    private MailSenderComponent mailSenderComponent;

    @PostMapping("/test-template")
    public String testTemplate(@RequestBody MailMessage message) {

        TemplateConfig config = querySrc.findConfigByCode(message.getTemplateCode());
        TemplateContent content = querySrc.findContent(config, message.getLocale());

        Map<String, Object> params = new HashMap<>();
        params.putAll(message.getParamters());
        return templateProcessFactory.getProcess(config.getType()).render(content.getData(), params);
    }

    @PostMapping("/send")
    public void send(@RequestBody MailMessage message) {
        mailSenderComponent.send(message);
    }
}
